/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.pa.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.seari.bean.pa.StationState;
import com.seari.pa.PaHelper;
import com.seari.utils.DataUtil;
import com.seari.utils.JedisPoolUtils;

/**
 *
 * @author Rainbow
 * pa解码器
 * 
 */
public class PaDecoder extends ByteToMessageDecoder
{
	
    protected static Logger logger = LoggerFactory.getLogger(PaDecoder.class);

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in,
			List<Object> out){
		//此帧的数据长度
		int readableBytes = in.readableBytes();
		
		//System.out.println(readableBytes);
		
		//首先判断此消息内容是否完整  判断是否超出长度
		 if(readableBytes < PaHelper.MAX_FRAME_LENGTH || readableBytes > PaHelper.MAX_PA_LENGTH)
	        {
			 if(readableBytes < PaHelper.MAX_FRAME_LENGTH){
				 logger.info("PA DATA maximun length of dily ! ");
			 }else{
				 logger.info(" PA  DATA length SO BIG!");
				 
			 }
			 //discardReadBytes() --> 丢弃读取的异常数据
			 	//in.discardReadBytes();
			 	//清空指针
			 	in.clear();
	            //消息内容不完整 , 直接返回
	            return;
	        }
		 // 处理数据
		byte[] bytes = new byte[readableBytes];
		in.readBytes(bytes);
        //再判断head是否完整
		 if(bytes[0] != (byte)0xeb && bytes[1] != (byte)0x90 )
	        {
			 
			 logger.info("PA RequestHead is not EB90 !!");
			 //in.discardReadBytes();
			 in.clear();
	            return ;
	        }
        
        out.add(bytes);
        logger.info("Data processing successful !! ..............");
        
        // 正文信息
        byte[] bodyBytes = DataUtil.subBytes(bytes,3,bytes.length - 4);
        /*正文部分每一个字节 , 一共20 字节 
         *  一个字节八个bit, 获取
         *  D0(连接位,1为已连接).
         *  D1(故障位,1为有故障).
         *  D2(广播位, 1 为有广播)
         *  D3 D4  D5 盒号 有广播置1 没有就0 注：3 个盒子只能同时开 2 个
         *  
         *  车站状态位操作封装到StationState
        */
        byte b = 0;
        StationState stationState  = null ;
        // 创建一个list集合 , 存储封装完成的StationState
     	List<StationState>list = new ArrayList<StationState>();
		for (int i = 0; i < bodyBytes.length; i++) {
			// 得到每一个字节
			b = bodyBytes[i];
			// 每一个字节的比特位数组
			byte[] booleanArray = PaDecoder.getBooleanArray(b);
			stationState = new StationState();
			stationState.setStationNum(String.valueOf(i+1));
			stationState.setD0(booleanArray[7]);
			stationState.setD1(booleanArray[6]);
			stationState.setD2(booleanArray[5]);
			stationState.setD3(booleanArray[4]);
			stationState.setD4(booleanArray[3]);
			stationState.setD5(booleanArray[2]);
			stationState.setD6(booleanArray[1]);
			//System.out.println(stationState);
			list.add(stationState);
			
	}
		
		
		Jedis jedis = null;
		try {
			jedis = JedisPoolUtils.getJedis();
			
			jedis.set("PaLine12", (JSON.toJSONString(list,SerializerFeature.DisableCircularReferenceDetect)));
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (jedis != null) {
				jedis.close();
			}
		}
		
	}
	
    
	/**
	 * 将byte转换为一个长度为8的byte数组，数组每个值代表bit
	 */
	public static byte[] getBooleanArray(byte b) {
		byte[] array = new byte[8];
		for (int i = 7; i >= 0; i--) {
			array[i] = (byte) (b & 1);
			b = (byte) (b >> 1);
		}
		return array;
	}
	
	
    
    
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
    
}
